﻿using MediatR;
using RBAC.Domain.RBAC;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.Role;

namespace RBAC.Write.Api.Application.Handler.Role
{
    public class UpdateRoleEnableHandler : IRequestHandler<UpdateRoleEnableCommand, APIResult<int>>
    {
        private readonly IBaseRepository<RoleModel> roleRepository;
        private readonly ILogger<UpdateRoleEnableHandler> logger;

        public UpdateRoleEnableHandler(IBaseRepository<RoleModel> roleRepository, ILogger<UpdateRoleEnableHandler> logger)
        {
            this.roleRepository = roleRepository;
            this.logger = logger;
        }
        /// <summary>
        /// 修改角色状态
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(UpdateRoleEnableCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var model = roleRepository.GetALL().FirstOrDefault(x => x.Id == request.Id);
            model.IsEnable = request.IsEnable;
            var r = roleRepository.Update(model);
            if (r > 0)
            {
                res.Data = r;
                res.Code = APIEnums.Success;
                res.Msg = "修改成功";
                logger.LogInformation("修改成功");
                return Task.FromResult(res);
            }
            else
            {
                res.Code = APIEnums.Fail;
                res.Msg = "修改失败";
                logger.LogError("修改失败");
                return Task.FromResult(res);
            }
        }
    }
}
